package com.carbon.common.service;

import cn.hutool.core.util.StrUtil;
import com.carbon.common.dao.SysSerialConfigDao;
import com.carbon.common.domain.SysSerialConfig;
import com.carbon.common.enums.SerialNoPrefix;
import com.carbon.exception.CarbonException;
import com.carbon.util.DateUtils;


import java.util.List;

/**
 * 流水号配置Service处理
 *
 * @author ljxl
 * @date 2022-06-23
 */
public class SysSerialConfigService {
    private static final Object LOCK = new Object();
    private SysSerialConfigDao sysSerialConfigDao;

    public SysSerialConfigService(){
        sysSerialConfigDao=new SysSerialConfigDao();
    }

    public String getSerialNo(SerialNoPrefix prefix) {
        SysSerialConfig sysSerialConfig = new SysSerialConfig();
        sysSerialConfig.setPrefix(prefix.name());
        long newNo = 0;
        String pre = null;
        synchronized (LOCK) {
            List<SysSerialConfig> configList = sysSerialConfigDao.selectSysSerialConfigList(sysSerialConfig);
            if (configList == null || configList.isEmpty()) {
                throw new CarbonException("获取流水号失败：未配置流水号规则");
            }
            SysSerialConfig config = configList.get(0);
            newNo = config.getMaxNo() + 1;
            pre = config.getPrefix();
            config.setMaxNo(newNo);
            sysSerialConfigDao.updateSysSerialConfig(config);
        }
        String serialNo = pre + DateUtils.dateTimeNow("yyyyMMdd") + StrUtil.padPre(String.valueOf(newNo), 6, "0");
        return serialNo;
    }

}
